import React from 'react';
import { ResponsiveContainer, ComposedChart, XAxis, YAxis, CartesianGrid, Tooltip, Bar } from 'recharts';

export interface CandlestickData {
  time: string;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
}

interface CandlestickChartProps {
  data: CandlestickData[];
}

interface CandlestickBarProps {
  payload?: CandlestickData;
  x?: number;
  y?: number;
  width?: number;
  height?: number;
}

const CandlestickBar = (props: CandlestickBarProps) => {
  const { payload, x = 0, y = 0, width = 0, height = 0 } = props;
  
  if (!payload || width === 0 || height === 0) return null;
  
  const { open, high, low, close } = payload;
  
  // 数据验证和安全检查
  const safeOpen = typeof open === 'number' && !isNaN(open) ? open : 0;
  const safeHigh = typeof high === 'number' && !isNaN(high) ? high : 0;
  const safeLow = typeof low === 'number' && !isNaN(low) ? low : 0;
  const safeClose = typeof close === 'number' && !isNaN(close) ? close : 0;
  
  // 确保价格范围有效
  const priceRange = safeHigh - safeLow;
  const hasValidRange = priceRange > 0;
  
  // 如果价格范围无效，使用默认显示
  if (!hasValidRange) {
    return (
      <rect
        x={x + width * 0.2}
        y={y + height / 2}
        width={width * 0.6}
        height={2}
        fill="#6b7280"
        opacity={0.5}
      />
    );
  }
  
  const isPositive = safeClose >= safeOpen;
  
  // 颜色
  const color = isPositive ? '#10b981' : '#ef4444'; // green or red
  
  return (
    <g>
      {/* 上下影线 */}
      <line
        x1={x + width / 2}
        y1={y + height * 0.1}
        x2={x + width / 2}
        y2={y + height * 0.9}
        stroke={color}
        strokeWidth={1}
      />
      
      {/* 蜡烛体 */}
      <rect
        x={x + width * 0.2}
        y={y + height * 0.3}
        width={width * 0.6}
        height={Math.max(2, height * 0.4)}
        fill={isPositive ? color : 'transparent'}
        stroke={color}
        strokeWidth={1}
      />
    </g>
  );
};

interface TooltipProps {
  active?: boolean;
  payload?: Array<{
    payload: CandlestickData;
  }>;
  label?: string;
}

const CustomTooltip = ({ active, payload, label }: TooltipProps) => {
  if (active && payload && payload.length) {
    const data = payload[0].payload;
    const isPositive = data.close >= data.open;
    
    return (
      <div className="bg-gray-800 border border-gray-600 rounded-lg p-3 shadow-lg">
        <p className="text-gray-300 text-sm mb-2">{`时间: ${label}`}</p>
        <div className="space-y-1 text-sm">
          <p className="text-gray-300">{`开盘: $${data.open.toFixed(6)}`}</p>
          <p className="text-gray-300">{`最高: $${data.high.toFixed(6)}`}</p>
          <p className="text-gray-300">{`最低: $${data.low.toFixed(6)}`}</p>
          <p className={`${isPositive ? 'text-green-400' : 'text-red-400'}`}>
            {`收盘: $${data.close.toFixed(6)}`}
          </p>
          <p className="text-gray-300">{`成交量: ${data.volume.toLocaleString()}`}</p>
        </div>
      </div>
    );
  }
  return null;
};

export const CandlestickChart: React.FC<CandlestickChartProps> = ({ data }) => {
  if (!data || data.length === 0) {
    return (
      <div className="h-64 bg-gray-800 rounded-lg flex items-center justify-center">
        <div className="text-center">
          <p className="text-gray-500 mb-2">暂无交易数据</p>
          <p className="text-gray-600 text-sm">进行一些交易后图表将显示价格走势</p>
        </div>
      </div>
    );
  }

  // 计算价格范围
  const allPrices = data.flatMap(d => [d.open, d.high, d.low, d.close]).filter(price => !isNaN(price) && isFinite(price));
  
  if (allPrices.length === 0) {
    return (
      <div className="h-64 bg-gray-800 rounded-lg p-4 flex items-center justify-center">
        <p className="text-gray-400">No valid price data available</p>
      </div>
    );
  }
  
  const minPrice = Math.min(...allPrices);
  const maxPrice = Math.max(...allPrices);
  const priceRange = maxPrice - minPrice;
  
  // 处理数据格式
  const chartData = data.map(item => {
    // 安全的价格值
    const safeOpen = isNaN(item.open) || !isFinite(item.open) ? minPrice : item.open;
    const safeHigh = isNaN(item.high) || !isFinite(item.high) ? maxPrice : item.high;
    const safeLow = isNaN(item.low) || !isFinite(item.low) ? minPrice : item.low;
    const safeClose = isNaN(item.close) || !isFinite(item.close) ? minPrice : item.close;
    
    // 如果价格范围为0（所有价格相同），设置为固定值
    if (priceRange === 0) {
      return {
        ...item,
        normalizedOpen: 0.5,
        normalizedHigh: 0.5,
        normalizedLow: 0.5,
        normalizedClose: 0.5,
      };
    }
    
    return {
      ...item,
      // 将价格标准化到 0-1 范围，方便绘制
      normalizedOpen: (safeOpen - minPrice) / priceRange,
      normalizedHigh: (safeHigh - minPrice) / priceRange,
      normalizedLow: (safeLow - minPrice) / priceRange,
      normalizedClose: (safeClose - minPrice) / priceRange,
    };
  });

  return (
    <div className="h-64 bg-gray-800 rounded-lg p-4">
      <ResponsiveContainer width="100%" height="100%">
        <ComposedChart data={chartData} margin={{ top: 10, right: 10, bottom: 10, left: 10 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
          <XAxis 
            dataKey="time" 
            axisLine={false}
            tickLine={false}
            tick={{ fill: '#9CA3AF', fontSize: 12 }}
          />
          <YAxis 
            domain={[minPrice * 0.99, maxPrice * 1.01]}
            axisLine={false}
            tickLine={false}
            tick={{ fill: '#9CA3AF', fontSize: 12 }}
            tickFormatter={(value) => `$${value.toFixed(6)}`}
          />
          <Tooltip content={<CustomTooltip />} />
          <Bar 
            dataKey="close" 
            shape={<CandlestickBar />}
            fill="transparent"
          />
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
};
